package com.springboot.util;


import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.Signature;
import java.security.interfaces.RSAPrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

/**
 * @Author: TongRui乀
 * @Date: 2019/6/26 15:00
 * @description： 创建签名 及 签名校验
 */
public class RSAUtils {

    public static final String CHARSET = "utf-8";

    /**
     * RSA私钥签名
     *
     * @param src 客户端传过来的原始参数
     * @param priKey  我们的客户端私钥
     * @return
     * @throws Exception
     */
    public static String sign (String src, String priKey) {
        try {
            KeyFactory fac = KeyFactory.getInstance("RSA");
            byte[] pribyte = Base64.getDecoder().decode(priKey);
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pribyte);
            RSAPrivateKey privateKey = (RSAPrivateKey) fac.generatePrivate(keySpec);

            Signature sigEng = Signature.getInstance("SHA1withRSA");
            sigEng.initSign(privateKey);
            sigEng.update(src.getBytes(CHARSET));

            byte[] signature = sigEng.sign();

            return org.apache.commons.codec.binary.Base64.encodeBase64String(signature);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * RSA公钥验证签名
     *
     * @param src  客户端穿过来的原始数据
     * @param sign  签名
     * @param publicKey 我们的客户端公钥
     * @return
     */
    public static boolean signVerify (String sign, String src, String publicKey) {
        try {
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");

            //将公钥变为一个字节数组
            byte[] encodedKey = Base64.getDecoder().decode(publicKey);
            //使用秘钥工厂生成一个公钥对象pubKey
            PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));

            //使用"SHA1WithRSA"算法,生成签名对象signature
            Signature signature = Signature.getInstance("SHA1WithRSA");
            signature.initVerify(pubKey);
            signature.update(src.getBytes(CHARSET));

            byte[] bytes = org.apache.commons.codec.binary.Base64.decodeBase64(sign);

            boolean bverify = signature.verify(bytes);
            return bverify;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


}
